﻿using AngleSharp.Css.Dom;
using MapleLeaf.Application.CookBook;
using MapleLeaf.Application.CookBook.Models;
using MapleLeaf.Core;
using MapleLeaf.Core.Dto;
using MapleLeaf.Core.Extension;
using MapleLeaf.Model.CookBook;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using MiniExcelLibs.OpenXml;
using SqlSugar;

namespace MapleLeaf.WebApi.CookBook.Controllers.CookBookManagement
{
    /// <summary>
    /// 食材管理
    /// </summary>
    public class IngredientController : ApiBaseController
    {
        private readonly CookBookManagementClient _managementClient;


        /// <summary>
        /// 
        /// </summary>
        public IngredientController(CookBookManagementClient managementClient)
        {
            _managementClient = managementClient;
        }


        #region 食材
        /// <summary>
        /// 获取所有食材
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<PaginationModel<IngredientVo>>> GetIngredientPageList(int pageNum, int pageSize)
        {
            var whereExp = Expressionable.Create<IngredientEntity>();
            PaginationModel pagination = new()
            {
                PageIndex = pageNum,
                PageSize = pageSize
            };
            var list = await _managementClient.GetIngredientPageListAsync(whereExp.ToExpression(), pagination);
            return Success(list);
        }
        /// <summary>
        /// 获取所有食材
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<IngredientVo>>> GetIngredientList()
        {
            var whereExp = Expressionable.Create<IngredientEntity>();
            //PaginationModel pagination = new() {
            //    PageIndex = pageNum,
            //    PageSize = pageSize
            //};
            var res = await _managementClient.GetIngredientListAsync(whereExp.ToExpression());
            var list = res.Adapt<List<IngredientVo>>();
            return Success(list);
        }
        /// <summary>
        /// 获取食材
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<IngredientEntity>> GetIngredientInfo(long id)
        {
            var result = await _managementClient.GetIngredientInfoAsync(id);
            return Success(result);
        }
        /// <summary>
        /// 保存食材
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> SaveIngredient(IngredientEntity entity)
        {
            var res = await _managementClient.SaveIngredientAsync(entity);

            return res ? Success() : Fail();
        }
        /// <summary>
        /// 删除食材
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> DeleteIngredient(List<long> ids)
        {
            var res = await _managementClient.DeleteIngredientAsync(p => ids.Contains(p.Id));
            return res ? Success() : Fail();
        }
        #endregion

        /// <summary>
        /// 导入食材
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Import(IFormFile file)
        {
            var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempfile");
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            var filefullPath = Path.Combine(dir, file.FileName);
            using (FileStream fs = new(filefullPath, FileMode.Create))
            {
                file.CopyTo(fs);
                fs.Flush();
            }
            var config = new OpenXmlConfiguration()
            {
                FillMergedCells = true
            };
            var rows = MiniExcel.Query(filefullPath, configuration: config).Cast<IDictionary<string, object>>();
            var headerRow = rows.FirstOrDefault();//第一行是表头
            var maps = new List<(string key, string name)>();
            foreach (var key in headerRow!.Keys)
            {
                maps.Add((key, headerRow[key]?.ToString() ?? ""));
            }

            var contentRows = rows.Skip(1).ToList();
            var list = new List<IngredientEntity>();
            foreach (var item in contentRows)
            {

                var entity = new IngredientEntity();

                entity.Name = item["A"]?.ToString() ?? "";
                if (entity.Name.IsNullOrEmpty())
                {
                    continue;
                }
                entity.Quantity = 0;
                list.Add(entity);
            }
            await _managementClient.InsertAsync(list);

            return Success(rows);
        }

    }
}
